package org.example.managementsystem.controller;

import org.example.managementsystem.model.*;
import org.example.managementsystem.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统计信息控制器
 */
@RestController
@RequestMapping("/api/statistics")
@CrossOrigin(origins = "*")
public class StatisticalInformationController {

    private final PersonService personService;

    @Autowired
    public StatisticalInformationController(PersonService personService) {
        this.personService = personService;
    }

    @Autowired
    private Product_PlanService productPlanService;
    @Autowired
    private Product_Plan_DetailService productPlanDetailService;
    @Autowired
    private Production_SubmissionService submissionService;
    @Autowired
    private Production_Submission_DetailService submissionDetailService;
    @Autowired
    private Production_ReviewService reviewService;

    /**
     * 获取计划完成情况统计
     * @return 包含整体、部门和员工计划完成情况的统计数据
     */
    @GetMapping("/plan-completion")
    public ResponseEntity<Map<String, Object>> getPlanCompletionStatistics() {
        Map<String, Object> statistics = new HashMap<>();
        Map<String, Double> departmentCompletion = new HashMap<>();
        Map<String, Double> employeeCompletion = new HashMap<>();

        // 获取所有计划明细
        List<Product_Plan_Detail> allPlanDetails = productPlanDetailService.getAllProduct_Plan_Details();
        
        // 计算总计划量
        int totalPlanned = allPlanDetails.stream()
                .mapToInt(Product_Plan_Detail::getProduct_quantity)
                .sum();

        // 获取所有已审批通过的提交
        List<Production_Submission> approvedSubmissions = submissionService.getAllProduction_Submissions().stream()
                .filter(submission -> {
                    Production_Review review = reviewService.getProduction_ReviewById(submission.getSubmission_id());
                    return review != null && review.isIs_approved();
                })
                .toList();

        // 计算总完成量和各部门、员工的完成情况
        int totalCompleted = 0;
        Map<String, Integer> departmentPlanned = new HashMap<>();
        Map<String, Integer> departmentCompleted = new HashMap<>();
        Map<String, Integer> employeePlanned = new HashMap<>();
        Map<String, Integer> employeeCompleted = new HashMap<>();

        // 统计各部门和员工的计划量
        for (Product_Plan_Detail detail : allPlanDetails) {
            Product_Plan plan = productPlanService.getProduct_PlanById(detail.getPlan_id());
            if (plan != null) {
                String department = plan.getDepartment();
                if (department != null) {
                    departmentPlanned.merge(department, detail.getProduct_quantity(), Integer::sum);
                    employeePlanned.merge(department, detail.getProduct_quantity(), Integer::sum);
                }
            }
        }

        // 统计各部门和员工的完成量
        for (Production_Submission submission : approvedSubmissions) {
            List<Production_Submission_Detail> details = submissionDetailService.getDetailsBySubmissionId(submission.getSubmission_id());
            int submissionTotal = details.stream()
                    .mapToInt(Production_Submission_Detail::getProduct_quantity)
                    .sum();
            
            totalCompleted += submissionTotal;

            // 获取提交对应的计划部门
            Long planId = submission.getPlan_id();
            Product_Plan plan = productPlanService.getProduct_PlanById(planId);
            if (plan != null) {
                String department = plan.getDepartment();
                if (department != null) {
                    departmentCompleted.merge(department, submissionTotal, Integer::sum);
                    employeeCompleted.merge(department, submissionTotal, Integer::sum);
                }
            }
        }

        // 计算完成率
        double totalCompletionRate = totalPlanned > 0 ? (double) totalCompleted / totalPlanned * 100 : 0;
        
        // 计算各部门完成率
        departmentPlanned.forEach((department, planned) -> {
            int completed = departmentCompleted.getOrDefault(department, 0);
            double completionRate = planned > 0 ? (double) completed / planned * 100 : 0;
            departmentCompletion.put(department, completionRate);
        });

        // 计算各员工完成率
        employeePlanned.forEach((jobNumber, planned) -> {
            int completed = employeeCompleted.getOrDefault(jobNumber, 0);
            double completionRate = planned > 0 ? (double) completed / planned * 100 : 0;
            employeeCompletion.put(jobNumber, completionRate);
        });

        // 组装返回数据
        statistics.put("totalPlanned", totalPlanned);
        statistics.put("totalCompleted", totalCompleted);
        statistics.put("totalCompletionRate", totalCompletionRate);
        statistics.put("departmentCompletion", departmentCompletion);
        statistics.put("employeeCompletion", employeeCompletion);

        return ResponseEntity.ok(statistics);
    }

    /**
     * 获取不同车间的人数统计
     * @return 车间名称和对应人数的键值对列表
     */
    @GetMapping("/department")
    public ResponseEntity<List<Map<String, Object>>> getPersonCountByDepartment() {
        List<Map<String, Object>> result = personService.countPersonsByDepartment();
        return ResponseEntity.ok(result);
    }

    /**
     * 获取不同最高学历的人数统计
     * @return 学历名称和对应人数的键值对列表
     */
    @GetMapping("/education")
    public ResponseEntity<List<Map<String, Object>>> getPersonCountByEducation() {
        List<Map<String, Object>> result = personService.countPersonsByEducation();
        return ResponseEntity.ok(result);
    }

    /**
     * 获取不同职称的人数统计
     * @return 职称名称和对应人数的键值对列表
     */
    @GetMapping("/title")
    public ResponseEntity<List<Map<String, Object>>> getPersonCountByTitle() {
        List<Map<String, Object>> result = personService.countPersonsByTitle();
        return ResponseEntity.ok(result);
    }
}

